using Microsoft.AspNetCore.Mvc.Filters;
using Vin.Tool.AspNetCore.Extension;

namespace Vin.Tool.AspNetCore.Attributes;

public enum HttpFieldType
{
    Header,
    Query,
    Form
}

/// <summary>
/// 标记该方法需要包含必传的Http属性
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class RequiredHttpField : Attribute, IAuthorizationFilter
{
    /// <summary>
    /// 属性所在位置
    /// </summary>
    public HttpFieldType FieldType { get; set; } = HttpFieldType.Header;

    /// <summary>
    /// 必传属性名称列表
    /// </summary>
    public string[] FieldNames { get; set; }

    public RequiredHttpField(params string[] fieldNames)
    {
        FieldNames = fieldNames;
    }

    public RequiredHttpField(HttpFieldType fieldType, params string[] fieldNames)
    {
        FieldType = fieldType;
        FieldNames = fieldNames;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        foreach (var fieldName in FieldNames)
        {
            if (!CheckFieldExists(context, fieldName))
            {
                context.InternalServerError($"缺少必传的{FieldType}属性: {fieldName}");
                return;
            }
        }
    }

    public bool CheckFieldExists(AuthorizationFilterContext context, string fieldName)
    {
        return FieldType switch
        {
            HttpFieldType.Header => context.HttpContext.Request.Headers.ContainsKey(fieldName),
            HttpFieldType.Query => context.HttpContext.Request.Query.ContainsKey(fieldName),
            HttpFieldType.Form => context.HttpContext.Request.HasFormContentType &&
                                  context.HttpContext.Request.Form.ContainsKey(fieldName),
            _ => false
        };
    }
}